home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 5788 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  83 lines

  1. Path: druid.borland.com!usenet
  2. From: pete@borland.com (Pete Becker)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Aborting Constructors, Part II
  5. Date: 6 Feb 1996 20:57:03 GMT
  6. Organization: Borland International
  7. Message-ID: <4f8fav$kik@druid.borland.com>
  8. References: <4eoeck$t6n@news.ios.com>
  9. NNTP-Posting-Host: pbecker.borland.com
  10. Mime-Version: 1.0
  11. Content-Type: Text/Plain; charset=ISO-8859-1
  12. X-Newsreader: WinVN 0.99.5
  13.  
  14. In article <4eoeck$t6n@news.ios.com>, leonardj@tribeca.ios.com says...
  15. >
  16. >
  17. >        Earlier, I posted a message about aborting a constructor if for some
  18. >reason some resource cannot be allocated. I did some thinking about
  19. >the problem and I thought, why couldn't you just call 'delete' inside
  20. >of the constructor itself and then let the destructor take care of the
  21. >release of all resources allocated so far. To find out whether or not
  22. >this would work, I wrote the following test program, compiled and ran
  23. >it under BC++ 4.52. It produced the output at the bottom of the page:
  24. >
  25. >//              File:           abort constructor test
  26. >
  27. >#include        <iostream.h>
  28. >#include        <except.h>
  29. >#include        <cstring.h>
  30. >
  31. >class           test{
  32. >        public:
  33. >                test();
  34. >                ~test();
  35. >};
  36. >
  37. >test::test(){
  38. >        cout << "constructing object\n";
  39. >        delete this;
  40. >        throw(xmsg(string("deleted the object!\n")));
  41. >}
  42. >
  43. >test::~test(){
  44. >        cout << "deleting object\n";
  45. >}
  46. >
  47. >void    main(){
  48. >
  49. >        try{
  50. >                test *at = new test;
  51. >        }
  52. >
  53. >        catch(xmsg error){
  54. >                cout << error.why();
  55. >        }
  56. >}
  57. >
  58. >        When compiled and run this produces the following output:
  59. >
  60. >constructing object
  61. >deleting object
  62. >deleted the object!
  63. >
  64. >        I'm guessing from this result that this is a valid way to do this. If
  65. >you have any opinion on this, especially if you happen to know of a
  66. >reason why this is not good, or conflicts somehow with what is
  67. >considered good C++ programming practice, I would like to know.
  68. >        Thanks
  69. >
  70.  
  71. Now try this variant of your program:
  72.  
  73. int main()
  74. {
  75.     test t;
  76.     return 0;
  77. }
  78.  
  79. Be prepared to reboot. No, the problem is not that there is no try block in 
  80. main.
  81.     -- Pete
  82.  
  83.